#include<iostream>
#include<sys/types.h>
#include<unistd.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
#include<vector>
#include"employee.h"
#include"department.h"
#include"servicedao_file_impl.h"

vector<Department>& ServiceDaoFileImpl::load(vector<Department>& departments)
{
	int fd = open("./account/services.dat",O_RDONLY,0644);
	if(0 > fd)
	{
		perror("open");
	}

	while(1)
	{

		int _id;
		int ret= read(fd,&_id,sizeof(int));
	//	cout <<_id <<" ";
		if(ret <= 0)
		{
			break;
		}
		int _len;
		int ret1= read(fd,&_len,sizeof(int));
	//cout <<_len<<" ";
		if(ret1 <= 0)
		{
			break;
		}
		char _name[20];
		int ret3 = read(fd,_name,_len);
		_name[_len] = '\0';
		//cout << _name << " ";
		if(ret3 <= 0)
		{
			break;
		}
		int _num;
		int ret4= read(fd,&_num,sizeof(int));
		//cout << _num << " ";
		if(ret4 <= 0)
		{
			break;
		}
		vector<Employee> emse;
		for(int i=0;i<_num;i++)
		{
			int e_id;
			read(fd,&e_id,sizeof(int));
//cout << e_id << " ";
			int e_len;
			read(fd,&e_len,sizeof(int));
//cout << e_len << " ";	
			char e_name[20];
			read(fd,e_name,e_len);
			e_name[e_len] = '\0';
//cout << e_name << " ";
			bool e_sex;
			read(fd,&e_sex,sizeof(bool));
//cout << e_sex << " ";
			int e_age;
			read(fd,&e_age,sizeof(int));
//cout << e_age << " ";
			Employee employee(e_id,e_name,e_sex,e_age);
			emse.push_back(employee);
		}

		Department department(_id,_name,emse);
		departments.push_back(department);
	}
	
	return departments;
}

void ServiceDaoFileImpl::save(vector<Department>& department)
{
	int fd = open("./account/services.dat",O_WRONLY,0644);
	for(unsigned int i =0; i<department.size(); i++)
	{
		int _id;
		_id = department[i].get_department_id();
		write(fd,&_id,sizeof(int));
		const char* p_name = department[i].get_department_name().c_str();
		int len_p_name = strlen(p_name);
		write(fd,&len_p_name,sizeof(int));
		write(fd,p_name,len_p_name);

		int num = department[i].get_department_ems().size();
		write(fd,&num,sizeof(int));
		for(unsigned int j=0; j<department[i].get_department_ems().size();j++ )
		{
			int e_id;
			e_id = department[i].get_department_ems()[j].get_employee_id();
			write(fd,&e_id,sizeof(int));
			const char* e_name = department[i].get_department_ems()[j].get_employee_name().c_str();
			int len_e_name = strlen(e_name);
			write(fd,&len_e_name,sizeof(int));
			write(fd,e_name,len_e_name);
			bool a =department[i].get_department_ems()[j].get_employee_sex();
			write(fd,&a,sizeof(bool));
			int b =department[i].get_department_ems()[j].get_employee_age();
			write(fd,&b,sizeof(int));
		}
		
	}



}
